const cors = require('cors');
const mongoHelper = require('../../lib/MongoHelper.js');
const mimeTypes = require('../../lib/mime-types.js');

const isEmpty = function(obj){
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) return false;
    }
    return true;
}

module.exports = function (router, settings) {
	let dfilecol = new mongoHelper.MongoCollection(settings['mongo_connect_url'], 'dfile', 5);
	const draft_col = new mongoHelper.MongoCollection(settings['mongo_connect_url'], 'draft', 5);
    const opus_col = new mongoHelper.MongoCollection(settings['mongo_connect_url'], 'opus', 5);

	router.get('/provider/get-article/:article_key', cors(), function(req, res){
		opus_col.get(req.params.article_key).then(doc=>{
			res.jsonp(doc||{});
		});
	});

	router.get('/provider/notify-published/:article_key/:publish_key', cors(), function(req, res){
		let _id = req.params.article_key;
		let doc = {
			'publish_key' : req.params.publish_key,
			'published': true,
			'publish_date': new Date()
		}
		opus_col.update(_id, doc, false, false).then(ret=>{
            if(ret.modifiedCount>0){
                draft_col.update(_id, doc, false, false).then(ret2=>{
                    if(ret2.modifiedCount>0){
                        res.jsonp({'success':true, 'message': 'notify successful'});
                    }else res.jsonp({'success':false, 'message': 'draft not found'});
                });
            }else res.jsonp({'success':false, 'message': 'article not found'});
        });
	});

	router.get('/static/dfile/:filename', cors(), (req,res)=>{
		let filename = req.params.filename;
		let extname;
		let dot_pos = filename.lastIndexOf('.');
		if(dot_pos>=0) extname = filename.substring(dot_pos);
		let files = [filename];
		if(filename.indexOf('$')>0){
			files = filename.substring(0, dot_pos||filename.length).split('$').map(x=>{return x + extname||'';});
		}
		
		let promises = files.map(f=>{return dfilecol.get({'name':f}, ['code','language']);});

		Promise.all(promises).then(results=>{
			if(results && results.length>0 && results.some(x=>{return !isEmpty(x);})){
				let combined_code = results.reduce((istr, result)=>{
					istr += result['code']?(result['code']+'\n'):'';
					return istr;
				},'');
				if(!extname)extname = results[results.length-1]['language'];
				let memetype = mimeTypes.lookup(extname) || 'application/octet-stream';
				res.set('Content-Type', memetype);
		        res.end(combined_code);
		    }else{
				// res.status(404).end();
				res.end();
			}
		});
	});
}